// import { createSlice, configureStore } from '@reduxjs/toolkit'
import { createSlice, configureStore, createAsyncThunk } from "./toolkit-redux";

export const fetchTodos = createAsyncThunk("todos/fetchTodos", async (value) => {
    // 这里的value是fetchTodos("xxx")参数值
    console.log(value)
  const response = await client.get("/fakeApi/todos");
  return response.todos;
});

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    value: 0,
  },
  reducers: {
    incremented: (state) => {
      // Redux Toolkit 允许在 reducers 中编写 "mutating" 逻辑。
      // 它实际上并没有改变 state，因为使用的是 Immer 库，检测到“草稿 state”的变化并产生一个全新的
      // 基于这些更改的不可变的 state。
      state.value += 1;
    },
    decremented: (state) => {
      state.value -= 1;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchTodos.pending, (state, action) => {
        state.status = "loading";
      })
      .addCase(fetchTodos.fulfilled, (state, action) => {
        const newEntities = {};
        action.payload.forEach((todo) => {
          newEntities[todo.id] = todo;
        });
        state.entities = newEntities;
        state.status = "idle";
      });
  },
});

export const { incremented, decremented } = counterSlice.actions;

const store = configureStore({
  reducer: counterSlice.reducer,
});

// 可以订阅 store
store.subscribe(() => console.log(store.getState()));

// 将我们所创建的 action 对象传递给 `dispatch`
store.dispatch(incremented());
// {value: 1}
store.dispatch(incremented());
// {value: 2}
store.dispatch(decremented());
// {value: 1}

// "xxx"值是传递给createAsyncThunk第二个方法的参数，就是上面的value值
store.dispatch(fetchTodos('xxx'))
